﻿using ADODB;
using fuzhu;
using LH.Model.PU;
using LH.Model.ST;
using SqlSuarEntity;
using SqlSugar;
using System.Data;
using U8COWeb;
using XXX.Bo;
using XXX.Common;
using XXX.Models;
using XXX.Models.U8Entity;
using XXX.Models.XXXEntities;
using ZDEntity;
using static System.Runtime.CompilerServices.RuntimeHelpers;

namespace Yonyou.U8.BO
{

    public class RdRecord11VM : ST_Rdrecord11
    {
        //当前的数据库连接字符串
        public string conStr { get; set; }
        public string xmlConfig { get; set; }
        public bool bWMS = false;
        public string cDatabase = "";

        public RdRecord11VM(Rd11Head head, List<Rd11Body> bodies) : base(head, bodies)
        {
            //conStr
            conStr = CanShu.conStr;
            //初始化定义xmlconfig
            xmlConfig = XmlOperation.GetConfigXML();
        }
         


        public RetModel2 AddVerify()
        {
            string idcheck = "";
            //if (Exists(ref idcheck))
            //{
            //    return DBService.ReErrObject($"当前单据号{this.head.ccode}已存在");
            //}
            foreach (Rd11Body body in bodies)
            {
                body.editprop = "A";
            }

            string cRe = GetAddInfo_FromApp();
            if (cRe != "ok")
            {
                return DBService.ReErrObject("获取基础信息失败:" + cRe);
            }
            SqlSugarClient db = new SqlSugarClient(new ConnectionConfig()
            {
                ConnectionString = conStr,
                DbType = SqlSugar.DbType.SqlServer,
                IsAutoCloseConnection = true
            });
            InventoryVM inventoryVM = new InventoryVM();
            HashSet<string> uniqueCinvCodes = new HashSet<string>();
            foreach (Rd11Body body in bodies)
            {
                body.editprop = "A";
                if (!string.IsNullOrEmpty(body.cinvcode))
                {
                    uniqueCinvCodes.Add(body.cinvcode);
                }
            }
            try
            { 
               
                //不是wms生成的，检查单据号是否存在
                if (!bWMS && Exists(ref idcheck))
                {
                   throw new Exception($"当前单据号{this.head.ccode}已存在");
                }
                // Step 1: 收集所有唯一的 cinvcode 
                inventoryVM.HandlerTopQty(db, uniqueCinvCodes);

                if (!Rdrecord11DALCO.AddVerifyRdrecord11(this, xmlConfig, out string err, out string id, out string ccode))
                {
                    //审核失败后，检查是否有采购入库单生成，如果有，则删除
                    string cerr2 = "";
                    if (!string.IsNullOrEmpty(id))
                    {
                        Rdrecord11DALCO.VerifyRdrecord11(id, xmlConfig, "delete", out cerr2);
                    }

                    throw new Exception("新增失败：" + err);
                }
                else
                {
                    DateTime dDate = DbHelper.GetDbDate(head.ddate);
                    int iid = DbHelper.GetDbInt(id);
                    db.Updateable<rdrecord11>()
                  .SetColumns(u => new rdrecord11()
                  {
                      dVeriDate = dDate,
                      cHandler = head.cmaker
                  })
                  .Where(u => u.ID == iid)
                  .ExecuteCommand();

                    ////不是wms的情况，检查单据号是不是传入的单据号（单据编码选项是 相同的就自动生成）。 如果不是，删除
                    //if (!bWMS)
                    //    {

                    //        if (ccode != head.ccode && head.ccode != WMSPara.rd01Code)
                    //        {
                    //            //单据编码选项判断
                    //            string sql = string.Format(@"Select  bRepeatReDo  From VoucherNumber Where CardNumber='0412'");
                    //            int iRepeat = DbHelper.GetDbInt(db.Ado.GetScalar(sql));
                    //            if (iRepeat == 1)
                    //            {
                    //                string cerr2 = "";
                    //                Rdrecord11DALCO.VerifyRdrecord11(id, xmlConfig, "unverify,delete", out cerr2);
                    //               throw new Exception("单据已生成，重复");
                    //            }
                    //        }
                    //    }
                    //    else
                    //    {
                    //        //wms的情况，因为保存是无单据号，根据传入的parentid进行判断。默认字段使用扩展自定义项10
                    //        string cParentid = head.cdefine10;
                    //        if (!string.IsNullOrEmpty(cParentid))
                    //        {
                    //            //检查cParentid 是否存在
                    //            string sqlcx = string.Format(@"select count(*) sl from rdrecord11 a  where  a.cdefine10='{0}' and a.id <>'{1}'", cParentid, id);
                    //            int icntUniq = DbHelper.GetDbInt(db.Ado.GetScalar(sqlcx));
                    //            if (icntUniq > 0)
                    //            {
                    //                Rdrecord11DALCO.VerifyRdrecord11(id, xmlConfig, "unverify,delete", out _);
                    //            throw new Exception("之前单据已生成，重复");
                    //            }
                    //        }

                    //    }

                }
                //生成的id赋值
                head.id = id;
                inventoryVM.UnHandlerTopQty(db, uniqueCinvCodes);
                return DBService.ReOKObject(ccode);
                //}
            }
            catch (Exception ex)
            {
                inventoryVM.UnHandlerTopQty(db, uniqueCinvCodes);
                return DBService.ReErrObject(ex.Message);
            }

        }

        public RetModel2 UnverifyDelete()
        {
            string ID = "";
            if (!Exists(ref ID))
            {
                
                return DBService.ReOKObject("当前单据号已删除");
            }
            else
            {
                head.id = ID;
            }
            //审核失败后，检查是否有采购入库单生成，如果有，则删除
            string cerr2 = "";
                if (!string.IsNullOrEmpty(head.id))
                {
                    if (!Rdrecord11DALCO.VerifyRdrecord11(head.id, xmlConfig, "unverify,delete", out cerr2))
                {
                    return DBService.ReErrObject("删除失败：" + cerr2);
                }
                }

                return DBService.ReOKObject("删除完成");
            
        }


        /// <summary>
        /// 材料出库单
        /// </summary>
        /// <param name="obj"></param>
        /// <param name="cErr"></param>
        /// <returns></returns>
        public RdRecord11VM GetAddEntity(API_Rdrecord obj, ref string cErr)
        {

            try
            {
                ST_Rdrecord11.Rd11Head head = new ST_Rdrecord11.Rd11Head
                {
                    bWireless = "1",
                    cvouchtype = "11",
                    cbustype = "材料出库",
                    csource = obj.cSource,
                    ccode = obj.cCode,
                    cwhcode = obj.cWhCode,
                    brdflag = "0",
                    //cdefine1 = obj.cCode,
                    ddate = DbHelper.GetDbDate(obj.dDate).ToString("yyyy-MM-dd"),
                    cpersoncode = obj.cPersonCode,
                    cdepcode = obj.cDepCode,
                    cmaker = obj.cMaker,
                    dveridate = DbHelper.GetDbDate(obj.dDate).ToString("yyyy-MM-dd"),
                    chandler = obj.cHandler,
                    cmemo = obj.cMemo,
                    crdcode = obj.cRdCode,
                    iswfcontrolled = "0",
                    vt_id = "65",
                    bomfirst = "0",
                    iPrintCount = "0",
                    cdefine1 = obj.cDefine1,
                    cdefine2 = obj.cDefine2,
                    cdefine3 = obj.cDefine3,
                    cdefine4 = obj.cDefine4,
                    cdefine5 = obj.cDefine5,
                    cdefine6 = obj.cDefine6,
                    cdefine7 = obj.cDefine7,
                    cdefine8 = obj.cDefine8,
                    cdefine9 = obj.cDefine9,
                    cdefine10 = obj.cDefine10,
                    cdefine11 = obj.cDefine11,
                    cdefine12 = obj.cDefine12,
                    cdefine13 = obj.cDefine13,
                    cdefine14 = obj.cDefine14,
                    cdefine15 = obj.cDefine15,
                    cdefine16 = obj.cDefine16,
                };


                List<LH.Model.ST.ST_Rdrecord11.Rd11Body> bodies = new List<LH.Model.ST.ST_Rdrecord11.Rd11Body>();
                if (obj.itemList != null && obj.itemList.Count > 0)
                {
                    using (SqlSugarClient db = new SqlSugarClient(new ConnectionConfig()
                    {
                        ConnectionString = conStr,
                        DbType = SqlSugar.DbType.SqlServer,
                        IsAutoCloseConnection = true
                    }))
                    {


                        int i = 0;
                        foreach (var item in obj.itemList)
                        {
                            if (string.IsNullOrEmpty(DbHelper.GetDbString(item.iQuantity)))
                            {
                                throw new Exception("数量不能为空");
                            }
                            if (string.IsNullOrEmpty(DbHelper.GetDbString(item.cInvCode)))
                            {
                                throw new Exception("存货编码不能为空");
                            }

                            i++;
                            ST_Rdrecord11.Rd11Body body = new ST_Rdrecord11.Rd11Body
                            {

                                cinvcode = item.cInvCode,
                                cfree1 = item.cFree1,
                                cfree2 = item.cFree2,
                                cfree3 = item.cFree3,
                                cfree4 = item.cFree4,
                                irowno = i.ToString(),
                                iquantity = DbHelper.GetDbString(item.iQuantity),
                                cbatch = item.cBatch,
                                cposition = item.cPosCode,
                                inum = DbHelper.GetDbString(item.iNum),
                                cbmemo = item.cBMemo,
                                citemcode = item.cItemCode,
                                citemcname = item.cItem_Name,
                                citem_class = item.cItem_Class,
                                //33自定义项作为mes行id
                                cdefine33 = item.cRowId,
                                cdefine32 = item.cSoureRowId,
                                //从22 写到37
                                cdefine22 = item.cDefine22,
                                cdefine23 = item.cDefine23,
                                cdefine24 = item.cDefine24,
                                cdefine25 = item.cDefine25,
                                cdefine26 = item.cDefine26,
                                cdefine27 = item.cDefine27,
                                cdefine28 = item.cDefine28,
                                cdefine29 = item.cDefine29,
                                cdefine30 = item.cDefine30,
                                cdefine31 = item.cDefine31,
                              

                                cdefine34 = item.cDefine34,
                                cdefine35 = item.cDefine35,
                                cdefine36 = item.cDefine36,
                                cdefine37 = item.cDefine37

                            };
                            //本次无关联单据
                            //if (cSource == "生产订单")
                            //{
                            //    body.impoids = DbHelper.GetDbString(lstnew[i].autoid);
                            //}


                            bodies.Add(body);
                        }
                    }
                }



                RdRecord11VM model = new RdRecord11VM(head, bodies);
                return model;

            }
            catch (Exception ex)
            {
                cErr = ex.Message;
                return null;
            }

        }

        /// <summary>
        /// 传入json转换成PurchaseOrderVM
        /// </summary>
        /// <param name="json"></param>
        /// <param name="cErr"></param>
        /// <returns></returns>
        public RdRecord11VM GetCodeEntity(API_Rdrecord obj, ref string cErr)
        {

            try
            {

                ST_Rdrecord11.Rd11Head head = new ST_Rdrecord11.Rd11Head();
                head.ccode = obj.cCode;
                List<ST_Rdrecord11.Rd11Body> bodies = new List<ST_Rdrecord11.Rd11Body>();

                RdRecord11VM model = new RdRecord11VM(head, bodies);

                return model;

            }
            catch (Exception ex)
            {
                cErr = ex.Message;
                return null;
            }





        }
        /// <summary>
        /// 威德封头用，传入生产订单号取信息，完善入库信息,处理部门，辅助计量单位
        /// </summary>
        /// <returns></returns>
        public string GetRd11InfoFromMo()
        {
            if (head == null)
            {
                return "Error: 没有数据";
            }
            if (bodies == null)
            {
                return "Error: 没有表体数据";
            }
            using (SqlSugarClient db = new SqlSugarClient(new ConnectionConfig()
            {
                ConnectionString = conStr,
                DbType = SqlSugar.DbType.SqlServer,
                IsAutoCloseConnection = true
            }))
            { 

                //取生产订单的部门，存货编码，工序信息
                MOrderVM orderVM = new MOrderVM();
                for (int i = 0;i<bodies.Count;i++)
                {
                    Rd11Body body = bodies[i];
                    mom_moallocate moallocate = orderVM.GetMoMaterialItem(body.cmocode, body.cinvcode);

                   //没有的，不需要生成出库单
                    if  (moallocate == null)
                    {
                        return "ok";
                    }
                    else
                    {

                        if (i==0)
                        {
                            mom_orderdetail orderdetail = orderVM.GetMoDetailItem(moallocate.MoDId);
                            head.cdepcode = orderdetail.MDeptCode; 
                        }
                        
                        body.impoids = DbHelper.GetDbString(moallocate.AllocateId);
                        body.imoseq = "1";
                        //设置默认批次,取工单号
                        if (string.IsNullOrEmpty(body.cbatch))
                        {
                            body.cbatch = body.cmocode;
                        }

                        body.cassunit = moallocate.AuxUnitCode;
                        //if(!string.IsNullOrWhiteSpace(body.inum) && body.inum!="0")
                        //{
                        //    body.iinvexchrate = DbHelper.GetDbString(DbHelper.GetDbdecimal(body.iquantity)/DbHelper.GetDbdecimal(body.inum));
                        //}
                        body.iinvexchrate = DbHelper.GetDbString(moallocate.ChangeRate);
                        //件数取weight
                        //if (!string.IsNullOrWhiteSpace(body.iinvexchrate) && moallocate.ChangeRate != 0.0m)
                        //{
                        //    body.inum = (DbHelper.GetDbdecimal(body.iquantity) / DbHelper.GetDbdecimal(body.iinvexchrate)).ToString("0.000000");
                        //}

                        #region 处理自由项6
                        string cInvCode = body.cinvcode;
                        Inventory inv = db.Queryable<Inventory>().Where(c => c.cInvCode == cInvCode).First();
                        if (inv == null)
                        {
                            return string.Format("Error: 第{0}行存货编码{1}不存在", (i + 1).ToString(), cInvCode);
                        }
                       
                        if (inv.bFree6)
                        {
                            if (string.IsNullOrWhiteSpace(body.cfree6))
                            {
                                return string.Format("Error: 第{0}行存货编码{1}有自由项6，长度管理，请录入", (i + 1).ToString(), cInvCode);
                            }

                        }
                        else
                        {
                            body.cfree6 = "";
                        }
                        #endregion

                    }


                }
                

                
            }
            
            return "ok";
        }

        /// <summary>
        /// 完善入库信息,处理部门，辅助计量单位
        /// </summary>
        /// <returns></returns>
        public string GetAddInfo_FromApp()
        {

            SqlSugarClient db = new SqlSugarClient(new ConnectionConfig()
            {
                ConnectionString = conStr,
                DbType = SqlSugar.DbType.SqlServer,
                IsAutoCloseConnection = true
            }); 
            try
            {
                
                 
                    for (int i = 0; i < bodies.Count; i++)
                    {
                        string cInvCode = bodies[i].cinvcode;

                        //有来源单据，处理表头和相关信息。如果没有，就只处理辅助计量单位及保质期
                        WMS_GetSource source = new WMS_GetSource();
                        if (head.csource == "领料申请单")
                        {

                            //int iSourceid = DbHelper.GetDbInt(bodies[i].imaids);
                            source = db.Queryable<MaterialAppVouchs>()
                            .InnerJoin<MaterialAppVouch>((a, b) => a.ID == b.ID && a.cDefine33 == bodies[i].cdefine32 )
                            .Select((a, b) => new WMS_GetSource
                            {
                                ID = b.ID,       
                                Autoid = a.AutoID,
                                cCode = b.cCode,
                                cDepCode = b.cDepCode,
                                cRdCode = b.cRdCode,
                                cPersonCode = b.cPersonCode,   
                                dDate = b.dDate,
                                cInvCode = a.cInvCode,
                                cUnitID = a.cAssUnit,
                                cMemo = b.cMemo,
                                cbMemo = a.cbMemo,
                                iChangeRate = a.iinvexchrate,
                                cMoCode = a.cmocode,
                                iMoSeq = a.imoseq,
                                iOpSeq =a.iopseq,
                                comocode =a.comcode,
                                ioMoDid =a.iOMoDID,
                                ioMoMid =a.iOMoMID,
                                cItem_class = a.cItem_class,
                                cItemCode = a.cItemCode,
                                cItemName = a.cName,
                                cItemCName = a.cItemCName,
                                cBatchProperty6 = a.cBatchProperty6,
                                cBatchProperty7 = a.cBatchProperty7
                            }).First();
                            if (source == null)
                            {
                                return string.Format("第{0}行领料申请单查询不到", (i + 1).ToString());
                            }

                            if (i == 0 && source != null)
                            {
                                head.cdepcode = source.cDepCode;
                                head.cpersoncode = source.cPersonCode;
                                if (!string.IsNullOrEmpty(source.cRdCode))
                                {
                                    head.crdcode = source.cRdCode;
                                }

                                head.cmemo = source.cMemo;
                                if (head.csource == "领料申请单")
                                {
                                    head.cbustype = "领料";
                                    head.cbuscode = source.cCode;
                                }

                            }

                            if (source.cInvCode != bodies[i].cinvcode)
                            {
                                return string.Format("第{0}行订单物料和{1}不一致", (i + 1).ToString(), cInvCode);
                            }

                        bodies[i].imaids = DbHelper.GetDbString(source.Autoid);
                        //没有检查自由项,是否和来源订单一样
                        bodies[i].cinvcode = source.cInvCode;
                            //bodies[i].cFree6 = source.cFree6;
                            bodies[i].cmocode = source.cMoCode;
                            bodies[i].imoseq = DbHelper.GetDbString(source.iMoSeq);
                            bodies[i].iopseq = source.iOpSeq;
                            bodies[i].comcode = source.comocode;
                            bodies[i].iomodid = DbHelper.GetDbString(source.ioMoDid);
                            bodies[i].iomomid = DbHelper.GetDbString(source.ioMoMid);


                            bodies[i].citemcname = source.cItemCName;
                            bodies[i].citemcode = source.cItemCode;
                            bodies[i].citem_class = source.cItem_class;
                            bodies[i].cname = source.cItemName;
                            bodies[i].cassunit = source.cUnitID;
                        }
                        else if (head.csource == "库存")
                    {

                       
                        source = db.Queryable<AA_BatchProperty>().Where(a=>a.cInvCode== cInvCode && a.cBatch== bodies[i].cbatch)
                        .Select(a => new WMS_GetSource
                        { 
                            cBatchProperty6 = a.cBatchProperty6,
                            cBatchProperty7 = a.cBatchProperty7
                        }).First(); 
                    }

                    InvProperty invProperty = new InventoryVM().GetInvProperty(cInvCode, bodies[i].dmadedate, bodies[i].dvdate);
                        if (invProperty == null)
                        {
                            return string.Format("第{0}行订单物料和{1}不存在", (i + 1).ToString(), cInvCode);
                        }
                        //iGroupType=0,无换算率，1,固定换算率，2,浮动换算率
                        if (invProperty.iGroupType != "0")
                        {
                            //辅助计量单位来源于来源单据，如果没有取库存单位
                            if (string.IsNullOrEmpty(bodies[i].cassunit))
                            {
                                bodies[i].cassunit = invProperty.cSTComUnitCode;
                            }

                            if (string.IsNullOrWhiteSpace(DbHelper.GetDbString(source.iChangeRate)))
                            {
                                bodies[i].iinvexchrate = invProperty.iChangRate;
                            }
                            else
                            {
                                bodies[i].iinvexchrate = DbHelper.GetDbString(source.iChangeRate);
                            }

                            if (!string.IsNullOrWhiteSpace(bodies[i].iinvexchrate) && DbHelper.GetDbdecimal(bodies[i].iinvexchrate) != 0.00m)
                            {
                                bodies[i].inum = (DbHelper.GetDbdecimal(bodies[i].iquantity) / DbHelper.GetDbdecimal(bodies[i].iinvexchrate)).ToString("0.000000");
                            }
                          
                        }

                        //是否批次管理
                        if (!invProperty.bInvBatch)
                        {
                            bodies[i].cbatch = "";
                        }
                        else if (string.IsNullOrEmpty(bodies[i].cbatch))
                        {
                            return string.Format("第{0}行订单物料{1}有批次管理，未录入批次", (i + 1).ToString(), cInvCode);
                        }
                        else
                    {
                        bodies[i].cbatchproperty6 = source.cBatchProperty6;
                        bodies[i].cbatchproperty7 = source.cBatchProperty7;
                    }
                        //自由项，未处理

                        //有效期管理,根据生产日期或者失效日期推算 
                        if (invProperty.bInvQuality)
                        {
                            if (string.IsNullOrEmpty(bodies[i].dmadedate) && string.IsNullOrEmpty(bodies[i].dvdate))
                            {
                                return string.Format("第{0}行订单物料生产日期或者失效日期未录入", (i + 1).ToString());
                            }
                            else
                            {
                                bodies[i].dvdate = DbHelper.GetDbDate(invProperty.dVDate).ToString("yyyy-MM-dd");
                                bodies[i].imassdate = DbHelper.GetDbString(invProperty.iMassDate);
                                bodies[i].cmassunit = DbHelper.GetDbString(invProperty.cMassUnit);
                                bodies[i].dexpirationdate = DbHelper.GetDbDate(invProperty.dExpeireDate).ToString("yyyy-MM-dd"); ;
                                bodies[i].iexpiratdatecalcu = DbHelper.GetDbString(invProperty.iexpiratdatecalcu);
                            }


                        }


                    }
                

            }
            catch (Exception ex)
            { 
                throw ex;
            }


            return "ok";
        }
        /// <summary>
        /// 检查销售单号是否存在
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public bool Exists(ref string id)
        {
            if (head == null)
            {
                return false;
            }
            
            using (SqlSugarClient db = new SqlSugarClient(new ConnectionConfig()
            {
                ConnectionString = conStr,
                DbType = SqlSugar.DbType.SqlServer,
                IsAutoCloseConnection = true
            }))
            {
                string sql = string.Format("select ID from rdrecord11 where ccode='{0}' ", head.ccode); 
                id = DbHelper.GetDbString(db.Ado.GetScalar(sql));

                 
                if (id == null)
                {
                    return false;
                }
                else
                {
                    return true;
                }
    
            } 
        
        }

         
    }
}
